/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef SMART_SERVE_SERVICES_SERVER_MODEL_MANAGER_H
#define SMART_SERVE_SERVICES_SERVER_MODEL_MANAGER_H

#include "model/creator.h"
#include "model/model.h"
#include <map>
#include <string>

namespace OHOS {
namespace SmartServe {

// 访问该类任意成员前置条件：已获取 Service::msMgmtMutex_
class ModelManager {
public:
    // 管理

    Model* GetOrCreateModel(const std::string& name);
    Model* GetModel(const std::string& name)
    {
        auto it = allModels_.find(name);
        return (it != allModels_.end()) ? it->second.get() : nullptr;
    }

    std::unique_ptr<Model> RemoveModel(Model* model)
    {
        std::unique_ptr<Model> ret = nullptr;

        auto it = allModels_.find(model->Name());
        if (it != allModels_.end()) {
            ret = std::move(it->second);
            allModels_.erase(it);
        }

        return ret;
    }

    // 注册

    bool Register(std::unique_ptr<ModelCreator> creator)
    {
        return registry_.insert({creator->Name(), std::move(creator)}).second;
    }

    bool UnRegister(const std::string& name)
    {
        return registry_.erase(name);
    }

    ModelCreator* GetCreator(const std::string& name)
    {
        auto it = registry_.find(name);
        if (it == registry_.end()) {
            return nullptr;
        }
        return it->second.get();
    }

    std::map<std::string, std::unique_ptr<Model>> allModels_;

private:
    std::map<std::string, std::unique_ptr<ModelCreator>> registry_;
};

} // namespace SmartServe
} // namespace OHOS

#endif // SMART_SERVE_SERVICES_SERVER_MODEL_MANAGER_H
